package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {

    @Autowired
    private DeptService deptService;

    @Autowired
    private EmpExprMapper empExprMapper;

    /**
     * 保存员工
     *
     * @param emp
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveEmp(Emp emp) {
        // 保存员工
        this.save(emp);
        // 删除员工经历
        empExprMapper.delete(Wrappers.<EmpExpr>lambdaQuery().eq(EmpExpr::getEmpId, emp.getId()));
        // 新增员工经历
        List<EmpExpr> exprList = emp.getExprList();
        if (!CollectionUtils.isEmpty(exprList)) {
            // 为员工经历赋值员工id
            exprList.forEach(empExpr -> empExpr.setEmpId(emp.getId()));
            // 开启新增
            empExprMapper.insert(exprList);
        }
    }

    /**
     * 分页查询
     *
     * @return
     */
    @Override
    public PageResult<Emp> myPage(EmpQueryParam param) {
        // 调用Service层查询分页数据
        Integer page = param.getPage();
        Integer pageSize = param.getPageSize();
        IPage<Emp> ipage = new Page<>(page, pageSize);

        // 分页
        LambdaQueryWrapper<Emp> wrapper = Wrappers.<Emp>lambdaQuery()
                .like(!param.getName().isEmpty(), Emp::getName, param.getName())
                .eq(param.getGender() != null, Emp::getGender, param.getGender())
                .between(param.getBegin() != null && param.getEnd() != null, Emp::getEntryDate, param.getBegin(), param.getEnd());
        wrapper.orderByDesc(Emp::getCreateTime);

        IPage<Emp> pageResult = this.page(ipage, wrapper);

        // 返回
        List<Emp> empList = pageResult.getRecords();
        long total = pageResult.getTotal();
        // 关联部门
        // 获取当前页部门id
        List<Integer> deptIds = empList.stream().map(Emp::getDeptId).toList();
        deptIds = deptIds.stream().distinct().toList();
        List<Dept> depts = deptService.listByIds(deptIds);


        empList.forEach(emp -> depts.stream()
                .filter(dept -> dept.getId().equals(emp.getDeptId()))
                .findFirst()
                .ifPresent(dept -> emp.setDeptName(dept.getName())));
        return new PageResult<>(total, empList);
    }

    /**
     * 批量删除员工
     *
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delereEmp(List<Integer> ids) {
        // 删除员工
        this.removeBatchByIds(ids);
        // 删除对应员工经历
        empExprMapper.delete(Wrappers.<EmpExpr>lambdaQuery().in(EmpExpr::getEmpId, ids));
    }

    /**
     * 根据id查询员工
     *
     * @param id
     * @return
     */
    @Override
    public Emp getEmpById(Integer id) {
        // 查询员工
        Emp emp = this.getById(id);
        // 查询员工经历
        List<EmpExpr> exprList = empExprMapper.selectList(Wrappers.<EmpExpr>lambdaQuery().eq(EmpExpr::getEmpId, id));
        emp.setExprList(exprList);
        return emp;
    }

    /**
     * 修改员工信息
     *
     * @param emp
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEmp(Emp emp) {
        // 补全数据,修改员工信息
        emp.setCreateTime(LocalDateTime.now());
        this.updateById(emp);
        // 删除员工经历
        empExprMapper.delete(Wrappers.<EmpExpr>lambdaQuery().eq(EmpExpr::getEmpId, emp.getId()));
        // 不为空新增员工经历
        List<EmpExpr> exprList = emp.getExprList();
        if (CollectionUtils.isNotEmpty(exprList)) {
            exprList.forEach(empExpr -> empExpr.setEmpId(emp.getId()));
            empExprMapper.insert(exprList);
        }
    }

    /**
     * 查询员工列表
     *
     * @return
     */
    @Override
    public List<Emp> selectEmpList() {
        return this.list();
    }
}
